#include <iostream>
#include "RringQueue.hpp"
#include "task.hpp"
#include <ctime>
#include <unistd.h>

struct ThreadData
{
    RingQueue<Task> *rq;
    std::string threadname;
};

void *Consumer(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    RingQueue<Task> *rq = td->rq;
    while (true)
    {
        // 消费数据
        Task t;
        rq->pop(&t);
        t.run();
        
        std::cout << "Consumer get task done, is : " << t.GetTask() << "result is : " << t.GetResult() << "thread is" << td->threadname << std::endl;
        //sleep(1);
    }

    return nullptr;
}

void *Productor(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    RingQueue<Task> *rq = td->rq;
    while (true)
    {
        int len = op.size();
        // 模拟生产者生产任务
        int data1 = rand() % 10 + 1;
        int data2 = rand() % 10;
        char oper = op[rand() % len];
        usleep(10);
        Task t(data1, data2, oper);

        rq->push(t);
        std::cout << "Productor task done, is : " << t.GetTask() << "thread is" << td->threadname << std::endl;
        sleep(1);
    }

    return nullptr;
}

int main()
{
    srand(time(nullptr) ^ getpid());
    pthread_t c[3], p[5];
    RingQueue<Task> *rq = new RingQueue<Task>();
    for (int i = 0; i < 1; i++)
    {
        ThreadData *td = new ThreadData();
        td->threadname = "Thread-" + std::to_string(i);
        td->rq = rq;
        pthread_create(c + i, nullptr, Consumer, td);
    }
    for (int i = 0; i < 1; i++)
    {
        ThreadData *td = new ThreadData();
        td->threadname = "Thread-" + std::to_string(i);
        td->rq = rq;
        pthread_create(p + i, nullptr, Productor, td);
    }

    for (int i = 0; i < 1; i++)
    {
        pthread_join(c[i], nullptr);
    }

    for (int i = 0; i < 1; i++)
    {
        pthread_join(p[i], nullptr);
    }

    return 0;
}